package idv.loveloser.servlet;

import idv.loveloser.dao.MdlAssignment;
import idv.loveloser.dao.MdlAssignmentDAO;
import idv.loveloser.dao.MdlContext;
import idv.loveloser.dao.MdlContextDAO;
import idv.loveloser.dao.MdlCourseModules;
import idv.loveloser.dao.MdlCourseModulesDAO;
import idv.loveloser.dao.MdlCourseSections;
import idv.loveloser.dao.MdlCourseSectionsDAO;
import idv.loveloser.dao.MdlEvent;
import idv.loveloser.dao.MdlEventDAO;
import idv.loveloser.dao.MdlGradeItems;
import idv.loveloser.dao.MdlGradeItemsDAO;
import idv.loveloser.util.Util;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class AddAssignment extends HttpServlet {
	private MdlCourseModulesDAO courseModulesDAO = new MdlCourseModulesDAO();
	private MdlAssignmentDAO assignmentDAO = new MdlAssignmentDAO();
	private MdlContextDAO contextDAO = new MdlContextDAO();
	private MdlEventDAO eventDAO = new MdlEventDAO();
	private MdlCourseSectionsDAO courseSctionDAO=new MdlCourseSectionsDAO();
	private MdlGradeItemsDAO gradesItemDAO = new MdlGradeItemsDAO();
	/**
	 * Constructor of the object.
	 */
	public AddAssignment() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		response.setCharacterEncoding("UTF-8");
		String client = request.getParameter("client");
		String sessionKey = request.getParameter("sessionKey");
		long grades = Long.parseLong(request.getParameter("grade"));
		String intro = request.getParameter("intro");
		String courseId=request.getParameter("courseId");
		if(courseId==null)
			courseId="1";
		String name=request.getParameter("name");
		short resubmit = (short) Integer.parseInt(request.getParameter("resubmit"));
		int days=Integer.parseInt(request.getParameter("due_days"));
		MdlAssignment assignment =new MdlAssignment();
		if(Util.isAuthorised(client, sessionKey)){
			MdlCourseModules courseModule = new MdlCourseModules();
			courseModule.setAdded(System.currentTimeMillis());
			courseModule.setAvailablefrom(0L);
			courseModule.setAvailableuntil(0L);
			courseModule.setCompletion(false);
			courseModule.setCompletionexpected(0L);
			courseModule.setCompletiongradeitemnumber(0L);
			courseModule.setCompletionview(false);
			courseModule.setCourse(Long.parseLong(courseId));
			courseModule.setGroupingid(0L);
			courseModule.setGroupmembersonly((short)0);
			courseModule.setGroupmode((short)0);
			courseModule.setIdnumber("");
			courseModule.setInstance(0L);
			courseModule.setModule(1L);
			courseModule.setScore((short)0);
			courseModule.setSection(0L);
			courseModule.setShowavailability(true);
			courseModule.setShowdescription(true);
			courseModule.setVisible(true);
			courseModule.setVisibleold(true);
			courseModule.setIndent(0);
			courseModulesDAO.save(courseModule);
			assignment =new MdlAssignment();
			assignment.setAssignmenttype("online");
			assignment.setCourse(Long.parseLong(courseId));
			assignment.setEmailteachers((short)0);
			assignment.setGrade(grades);
			assignment.setIntro(intro);
			assignment.setIntroformat((short)1);
			assignment.setMaxbytes(100000L);
			assignment.setName(name);
			assignment.setPreventlate((short)0);
			assignment.setResubmit(resubmit);
						
			assignment.setTimeavailable(getNextDay());
			assignment.setTimedue(calculateCalendar(days));
			assignment.setVar1(0L);
			assignment.setVar2(0L);
			assignment.setVar3(0L);
			assignment.setVar4(0L);
			assignment.setVar5(0L);
			assignment.setTimemodified(System.currentTimeMillis());
			assignmentDAO.save(assignment);
			List<MdlCourseSections> sections=courseSctionDAO.findByCourse(Long.parseLong(courseId));
			for(int index=0;index<sections.size();index++){
				if(sections.get(index).getSection()==0L){
					String sequence = sections.get(index).getSequence()+","+courseModule.getId();
					sections.get(index).setSequence(sequence);
					courseSctionDAO.merge(sections.get(index));
					break;
				}
			}
			courseModule.setInstance(assignment.getId());
			courseModulesDAO.merge(courseModule);
			MdlContext context =new MdlContext();
			context.setContextlevel(70L);
			context.setInstanceid(courseModule.getId());
			context.setDepth((short)0);
			context.setPath(null);
			contextDAO.save(context);
			int contextDepth=-1;
			String path="";
			
			List<MdlContext>contexts=contextDAO.findByContextlevel(50L);
			for(int index=0;index<contexts.size();index++){
				if(contexts.get(index).getInstanceid()==1){
					contextDepth=contexts.get(index).getDepth()+1;
					path=contexts.get(index).getPath();
					break;
				}
			}
			context.setDepth((short)contextDepth);
			context.setPath(path+"/"+context.getId());
			contextDAO.merge(context);
			MdlEvent event = new MdlEvent();
			event.setCourseid(courseModule.getCourse());
			event.setDescription(intro);
			event.setEventtype("due");
			event.setFormat((short)1);
			event.setGroupid(0L);
			event.setInstance(courseModule.getInstance());
			event.setModulename("assignment");
			event.setName(name);
			event.setRepeatid(0L);
			event.setSequence(1L);
			event.setTimeduration(0L);
			event.setTimemodified(System.currentTimeMillis());
			event.setTimestart(getNextDay());
			event.setUserid(Util.getUserId(Long.parseLong(client)));
			event.setUuid("");
			event.setVisible((short)1);
			eventDAO.save(event);
			MdlGradeItems item = new MdlGradeItems();
			item.setAggregationcoef(0.0D);
			item.setCalculation("");
			item.setCategoryid(2L);
			item.setCourseid(1L);
			item.setDecimals(false);
			item.setDisplay(0L);
			item.setGrademax((double)assignment.getGrade());
			item.setGrademin(0.0);
			item.setGradepass(0.0);
			item.setGradetype((short)1);
			item.setHidden(0L);
			item.setIdnumber("0");
			item.setIteminfo("");
			item.setIteminstance(assignment.getId());
			item.setItemmodule("assignment");
			item.setItemname(assignment.getName());
			item.setItemnumber(0L);
			item.setItemtype("mod");
			item.setLocked(0L);
			item.setLocktime(0L);
			item.setMultfactor(1.00000d);
			item.setNeedsupdate(0L);
			item.setOutcomeid(0L);
			item.setPlusfactor(0d);
			item.setScaleid(0L);
			item.setSortorder(getMaxSortOrderFromGradeItem());
			item.setTimecreated(System.currentTimeMillis());
			item.setTimemodified(System.currentTimeMillis());
			gradesItemDAO.save(item);
		}
		Gson gson = new Gson();
		out.println(gson.toJson(assignment));
		
		out.flush();
		out.close();
	}
	private long getNextDay(){
		Calendar tomorrow = Calendar.getInstance();
		tomorrow.set(Calendar.HOUR,23 );
		tomorrow.set(Calendar.MINUTE,59 );
		tomorrow.set(Calendar.SECOND,59 );
		return tomorrow.getTimeInMillis()/1000;
	}
	private long getMaxSortOrderFromGradeItem(){
		long max =-1;
		List<MdlGradeItems>items=gradesItemDAO.findByCourseid(1L);
		for(int index=0;index<items.size();index++){
			if(items.get(index).getSortorder()>max)
				max=items.get(index).getSortorder();
		}
		return max;
	}
	private long calculateCalendar(int dueDaysInt){
		
		Calendar tomorrow = Calendar.getInstance();
		
		tomorrow.set(Calendar.HOUR,23 );
		tomorrow.set(Calendar.MINUTE,59 );
		tomorrow.set(Calendar.SECOND,59 );
//		int dueDays=Integer.parseInt(dueDaysStr);
		long addLong = 86400*dueDaysInt*1000;
		addLong=tomorrow.getTimeInMillis()+addLong;
		return addLong/1000;
	}
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
